<template>
  <div>
		<el-form :inline="true" ref="dataFormRef"  :model="param.dataForm" @keyup.enter.native="getDataList()">
			<el-form-item v-if="istenant && userInfos.tenantId === '1'" prop="tenantName" label="租户名称">
                <el-input v-model="param.dataForm.tenantName" placeholder="租户名称" clearable>
                </el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="param.dataForm.username" placeholder="用户名" clearable></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="staffName">
                <el-input v-model="param.dataForm.staffName" placeholder="姓名" clearable></el-input>
            </el-form-item>
            <el-form-item >
			<el-button type="primary" icon="ele-Search" @click="getDataList()">搜索</el-button>
            <el-button type="primary" icon="ele-Refresh" @click="reSetForm(dataFormRef)">重置</el-button>
			</el-form-item>
		</el-form>
		<div class="btnStyle">
            <div>
				<el-button  type="success" icon="ele-Plus" @click="addHandle()">新增</el-button>
				<el-button  type="primary" icon="ele-Edit" @click="updateHandle()" :disabled="dataListSelections.length !== 1">修改</el-button>
				<el-button  type="primary" icon="ele-Edit" @click="userStationSetHandle()" :disabled="dataListSelections.length !== 1">设置岗位</el-button>
				<el-button  type="primary" icon="ele-Edit" @click="userResSetHandle()" :disabled="dataListSelections.length !== 1">设置资源权限</el-button>
				<el-button  type="danger" icon="ele-Edit" @click="resetPassword()" :disabled="dataListSelections.length !== 1">重置密码</el-button>
				<el-button  type="danger" icon="ele-Delete" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">删除</el-button>
            </div>
        </div>
		<el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle" style="width: 100%;">
			<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
			<el-table-column v-if="istenant && userInfos.tenantId === '1'" prop="tenant_name" header-align="center" align="center" label="租户"></el-table-column>
			<el-table-column prop="username" header-align="center" align="center" label="用户名"></el-table-column>
			<el-table-column prop="staff_id" header-align="center" align="center" label="员工编号"></el-table-column>
			<el-table-column prop="staff_name" header-align="center" align="center" label="姓名"></el-table-column>
			<el-table-column prop="email" header-align="center" align="center" label="邮箱"></el-table-column>
			<el-table-column prop="mobile" header-align="center" align="center" label="手机号"></el-table-column>
			<el-table-column prop="status" header-align="center" align="center" label="状态" :formatter="formatStatus" ></el-table-column>
			<el-table-column prop="create_time" header-align="center" align="center" width="180" label="创建时间" :formatter="dateFormatYMDHMS" >
			</el-table-column>
		</el-table>
		<el-pagination
			@size-change="onSelectSizeChange"
			@current-change="onSelectCurrentChange"
			:pager-count="5"
			:page-sizes="[10, 50, 200]"
			v-model:current-page="param.page"
			background
			v-model:page-size="param.limit"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total" small>
		</el-pagination>

		<AddOrUpdate ref="addOrUpdateRef" @refreshDataList="getDataList" />
		<SetUserStation ref="userStationSetRef" @refreshDataList="getDataList"></SetUserStation>
		<SetUserRes ref="userResSetRef" @refreshDataList="getDataList"></SetUserRes>
  </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, nextTick, defineComponent } from 'vue'
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import type { FormInstance, ElTree } from 'element-plus'
import {systemApi} from '/@/api/systemapi'
import commonFunction from '/@/utils/commonFunction';
import { getCodeList } from '/@/utils/cacheDict'
import AddOrUpdate from "./addOrUpdateUser.vue"
import SetUserStation from "./editUserStation.vue"
import SetUserRes from "./editUserRes.vue"
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
export default defineComponent({ 
	components: { AddOrUpdate, SetUserStation, SetUserRes },
	setup() {
		const stores = useUserInfo()
		const { userInfos } = storeToRefs(stores)
		const dataFormRef = ref<FormInstance>()
		const addOrUpdateRef = ref()
		const userStationSetRef = ref()
		const userResSetRef = ref()
		const { dateFormatYMDHMS } = commonFunction();
		const state = reactive({
			istenant: import.meta.env.VITE_IS_TENANT,
			total: 0,
			param: {
				page: 1,
				limit: 10,
				dataForm: {
					username: '',
					staffId: '',
					staffName: '',
					tenantName: ''
				}
			},
			dataList: [],
			dataListLoading: false,
			dataListSelections: [],
			dataDictionaryList: {},
		})
		// 页面加载时
		onMounted(() => {
			// 数据字典
			getCodeList(state, ['1002'])
			// 列表查询
			getDataList()
		})
		const getDataList = () =>{
			state.dataListLoading = true;
			nextTick(() => {
				systemApi().queryUserListCouncil(state.param).then(data => {
					if (data && data.code === 0) {
						state.dataList = data.page.list;
						state.total = data.page.totalCount;
					} else {
						state.dataList = [];
						state.total = 0;
					}
				}).catch(() => {
				}).finally(() => {
					state.dataListLoading = false;
				})
			});
		}
		//重置
		const reSetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			state.param.page = 1
			getDataList()
		}
		const addHandle = () => {
			addOrUpdateRef.value.openDialog('', userInfos.value.tenantId)
		}
		const updateHandle = () => {
			addOrUpdateRef.value.openDialog(state.dataListSelections[0].id, state.dataListSelections[0].tenant_id)
		}
		const userStationSetHandle = () => {
			userStationSetRef.value.openDialog(state.dataListSelections[0].id, state.dataListSelections[0].tenant_id)
		}
		const userResSetHandle = () => {
			userResSetRef.value.openDialog(state.dataListSelections[0].id, state.dataListSelections[0].tenant_id)
		}
		const resetPassword = () => {
			ElMessageBox.confirm('是否确定重置用户密码', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				var ids = state.dataListSelections.map(item => {
					return item.id
				})
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				systemApi().resetPassword(ids[0]).then(data => {
					if (data && data.code === 0) {
						ElMessageBox.alert('密码重置成功，重置后密码为：' + data.random + '。请牢记并通知用户尽快修改！', '提示', {
							confirmButtonText: '确定'
						})
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error('重置密码失败！')
				}).finally(() => {
					loading.close()
				})
			})
		}
		const deleteHandle = (id: any) => {
			ElMessageBox.confirm('是否确定删除用户', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				var userIds = id ? [id] : state.dataListSelections.map(item => {
					return item.id
				})
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				systemApi().deleteUserInfo(userIds).then(data => {
					if (data && data.code === 0) {
						ElMessage.success('删除成功！')
						getDataList()
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error('删除失败！')
				}).finally(() => {
					loading.close()
				})
			})
		}
		const selectionChangeHandle = (val: any) => {
			state.dataListSelections = val
		}
		const formatStatus = (row:any, column:any, cellValue:any, index:number) => {
			if (cellValue) {
				// return cellValue
				return state.dataDictionaryList['1002'][cellValue]
			}
		}
		// 分页改变
		const onSelectSizeChange = (val: number) => {
			state.param.limit = val
			getDataList()
		}
		// 分页改变
		const onSelectCurrentChange = (val: number) => {
			state.param.page = val;
			getDataList()
		}
		return {
			userInfos,
			dataFormRef,
			getDataList,
			reSetForm,
			addHandle,
			updateHandle,
			userStationSetHandle,
			userResSetHandle,
			resetPassword,
			deleteHandle,
			selectionChangeHandle,
			formatStatus,
			dateFormatYMDHMS,
			onSelectSizeChange,
			onSelectCurrentChange,
			addOrUpdateRef,
			userStationSetRef,
			userResSetRef,
			...toRefs(state),
		}
	}
})
</script>

<style>

</style>